package com.example.design.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private static String TOKEN = "token!Q@W3e4r";

    /**
     * 生成token
     *
     * @param map //传入payload
     * @return 返回token
     */
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 7);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    /**
     * 获取token中payload
     *
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    public static void main(String[] args) {
        // 登录接口登录成功调用
        Map<String, String> map = new HashMap<>();//用来存放payload
        map.put("id", "123");
        map.put("username", "zhangsan");
        String token = JWTUtils.getToken(map);
        System.out.println("token:" + token);

        // 访问其他接口前需要授权才能访问，可以把下面的代码放到拦截器里
        try {
            JWTUtils.verify(token);
            System.out.println("验证通过~~~");
        } catch (TokenExpiredException e) {
            System.out.println("Token已经过期!!!");
        } catch (SignatureVerificationException e) {
            System.out.println("签名错误!!!");
        } catch (AlgorithmMismatchException e) {
            System.out.println("加密算法不匹配!!!");
        } catch (Exception e) {
            System.out.println("无效token~~");
            e.printStackTrace();
        }
    }
}